/*************************
 *  Code writen by Nils Ericson 2011
 *  This is a Android app to report observation to Artportalen
 ******************/

package art.up;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.view.View.OnClickListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


public class ArtupActivity extends Activity {
	
	public void raportView() {
		setContentView(R.layout.main);
        TextView t;
		t=(TextView)findViewById(R.id.datumv); 
	    t.setText(this.getDate());
        
        if (this.isOnline()) {
        	Toast.makeText( getApplicationContext(), "Online", 100000).show();
        	
        } else {
        	Toast.makeText( getApplicationContext(), "Offline", 100000).show();
        }
        
        SharedPreferences settings = getPreferences(0);
	    String lokal = settings.getString("lokal", "");
		t=(TextView)findViewById(R.id.lokal); 
	    t.setText(lokal);
        
        final Button button = (Button) findViewById(R.id.button_rapportera);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks
				readWebpage();
            }
        });
        
        final Button button2 = (Button) findViewById(R.id.button_inst);
        button2.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks
            	instView();
            }
        });
        

        LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        LocationListener myLocationListener = new LocationListener() {
        		
        	@Override
        	public void onLocationChanged(Location loc)
        	{
        		float acc = loc.getAccuracy();
        		Coordinate z = new Coordinate();
        		
        		TextView t;
        		t=(TextView)findViewById(R.id.wnorthcoord); 
        	    t.setText(loc.getLatitude()+"");
        	    t=(TextView)findViewById(R.id.weastcoord); 
        	    t.setText(loc.getLatitude()+"");
        	    t=(TextView)findViewById(R.id.waccoord); 
        	    t.setText(acc+"");
        	    
        	    z.setXY(loc.getLatitude(), loc.getLongitude());
        		z.WGS84toRT90();
        		
        		t=(TextView)findViewById(R.id.northcoord); 
        	    t.setText(Math.round(z.getNorth())+"");
        	    t=(TextView)findViewById(R.id.eastcoord); 
        	    t.setText(Math.round(z.getEast())+"");
        	    t=(TextView)findViewById(R.id.accoord); 
        	    t.setText(acc+"");
        	    
        	}

        	@Override
        	public void onProviderDisabled(String provider)
        	{
        		Toast.makeText( getApplicationContext(), "The Gps is Disabled", Toast.LENGTH_LONG ).show();
        	}

        	@Override
        	public void onProviderEnabled(String provider)
        	{
        		Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_LONG).show();
        	}

        	@Override
        	public void onStatusChanged(String provider, int status, Bundle extras)
        	{
        		Toast.makeText( getApplicationContext(), "GPS status changed", Toast.LENGTH_LONG).show();
        	}
        };

        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
	}
	
	public void instView() {
		setContentView(R.layout.inst);
		
		SharedPreferences settings = getPreferences(0);
	    String username = settings.getString("username", "");
	    String pswrd = settings.getString("username2", "");
	    int ngri = settings.getInt("nogri", 4);
		TextView t;
		t=(TextView)findViewById(R.id.userName); 
	    t.setText(username);
	    t=(TextView)findViewById(R.id.pswrd); 
	    t.setText(pswrd);
		
	    Spinner ngrsp = (Spinner) findViewById(R.id.nogr);
	    ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.nogr , android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    ngrsp.setAdapter(adapter);
	    ngrsp.setSelection(ngri);

	    final Button buttonok = (Button) findViewById(R.id.button_ok);
	    buttonok.setOnClickListener(new OnClickListener() {
	         public void onClick(View v) {
	                  // Perform action on clicks
	        	TextView t;
	     		t=(TextView)findViewById(R.id.userName);
	     		String userNme = t.getText().toString();
	     		t=(TextView)findViewById(R.id.pswrd);
	     		String pswrd = t.getText().toString();
	     		Spinner ngrsp = (Spinner)findViewById(R.id.nogr);
	     		String nogr = ngrsp.getSelectedItem().toString();
	     		int nogrIndex = ngrsp.getSelectedItemPosition();
	        	 
	            SharedPreferences settings = getPreferences(0);
	            SharedPreferences.Editor editor = settings.edit();
	            editor.putString("username", userNme);
	            editor.putString("username2", pswrd);
	            editor.putString("nogr", nogr);
	            editor.putInt("nogri", nogrIndex);
	            
	            editor.commit();
	        	raportView();
	         }
	    });
	}
	
	public String getDate() {
		Calendar calendar = new GregorianCalendar();
        Date time = new Date();
        //SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-DD");
        //String s = formatter.format(time);
        calendar.setTime(time);
        String month = Integer.toString(calendar.get(Calendar.MONTH));
        if (month.length() ==1) month="0"+month;
        String dag = Integer.toString(calendar.get(Calendar.DATE));
        if (dag.length() ==1) dag="0"+dag;
        String datestring = Integer.toString(calendar.get(Calendar.YEAR))+'-'+month+'-'+dag;
        return datestring;
        //return s;
	}
	
	public boolean isOnline() {
		 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		 NetworkInfo netInfo = cm.getActiveNetworkInfo();
		 if (netInfo != null && netInfo.isConnectedOrConnecting()) {
		      return true;
		 }
		 return false;
	}
	
	private String rapportera(String userName, String password, String art, String N, String E, String datum, String lokal, String ngr, int portal) throws IOException {
		String data = URLEncoder.encode("txtFieldLoginname", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8");
	    data += "&" + URLEncoder.encode("txtFieldPassword", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
		
		  URL site = new URL("http://www.artportalen.se/plants/login_check.asp");
		  URLConnection conn = site.openConnection();
		  conn.setRequestProperty ( "User-agent", "artup");
		  conn.setDoOutput(true);
		  OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		  wr.write(data);
		  wr.flush();
		  BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
		  String response = "";
			String s;
			while ((s = rd.readLine()) != null) {
				response += s;
			}
			rd.close();
			
		  String cookies = new String();
			for (int i=0; ; i++) {
		        String headerName = conn.getHeaderFieldKey(i);
		        String headerValue = conn.getHeaderField(i);

		        if (headerName == null && headerValue == null) {
		            // No more headers
		            break;
		        }
		        if ("Set-Cookie".equalsIgnoreCase(headerName)) {
		        	cookies += headerValue +"; ";

		        }
		    }
			site = new URL("http://www.artportalen.se/plants/vobs.asp");
			
			/*
			 * xk=
			 * &yk=
			 * &exactitude=
			 * &visayta=0
			 * &visaAntalSubstrat=0
			 * &koordtyp=0
			 * &visaslutdat=0
			 * &visaherbarie=0
			 * &visaaccessionsnr=0
			 * &visakommentar=0
			 * &visadeterminator=0
			 * &visasmallfields=0
			 * &visaantalrader=5
			 * &visasubstrat=0
			 * &medobsid=
			 * &syfteid=0
			 * &presentInputField=art1
			 * &art1=lunglav
			 * &antal1=
			 * &sel_enhet1=0
			 * &lokalnamn1=artup
			 * &biotop1=
			 * &ykoord1=6994874
			 * &xkoord1=1564026
			 * &exactitude1=250
			 * &from1=2010-07-07
			 * &stadie1=0
			 * 
			 * &art2=&antal2=&sel_enhet2=0&lokalnamn2=&biotop2=&ykoord2=&xkoord2=&exactitude2=0&from2=&stadie2=0&art3=&antal3=&sel_enhet3=0&lokalnamn3=&biotop3=&ykoord3=&xkoord3=&exactitude3=0&from3=&stadie3=0&art4=&antal4=&sel_enhet4=0&lokalnamn4=&biotop4=&ykoord4=&xkoord4=&exactitude4=0&from4=&stadie4=0&art5=&antal5=&sel_enhet5=0&lokalnamn5=&biotop5=&ykoord5=&xkoord5=&exactitude5=0&from5=&stadie5=0
			 */
			
			data = URLEncoder.encode("xk", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
		    data += "&" + URLEncoder.encode("yk", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
		    data += "&" + URLEncoder.encode("exactitude", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
		    data += "&" + URLEncoder.encode("visayta", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visaAntalSubstrat", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("koordtyp", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visaslutdat", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visaherbarie", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visaaccessionsnr", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visakommentar", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visadeterminator", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visasmallfields", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("visaantalrader", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8");
		    data += "&" + URLEncoder.encode("visasubstrat", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("medobsid", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
		    data += "&" + URLEncoder.encode("syfteid", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("presentInputField", "UTF-8") + "=" + URLEncoder.encode("art1", "UTF-8");
		    data += "&" + URLEncoder.encode("art1", "UTF-8") + "=" + URLEncoder.encode(art, "UTF-8");
		    data += "&" + URLEncoder.encode("antal1", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
		    data += "&" + URLEncoder.encode("sel_enhet1", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    data += "&" + URLEncoder.encode("lokalnamn1", "UTF-8") + "=" + URLEncoder.encode(lokal, "UTF-8");
		    data += "&" + URLEncoder.encode("biotop1", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8");
		    data += "&" + URLEncoder.encode("ykoord1", "UTF-8") + "=" + URLEncoder.encode(N, "UTF-8");
		    data += "&" + URLEncoder.encode("xkoord1", "UTF-8") + "=" + URLEncoder.encode(E, "UTF-8");
		    data += "&" + URLEncoder.encode("exactitude1", "UTF-8") + "=" + URLEncoder.encode(ngr, "UTF-8");
		    data += "&" + URLEncoder.encode("from1", "UTF-8") + "=" + URLEncoder.encode(datum, "UTF-8");
		    data += "&" + URLEncoder.encode("stadie1", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8");
		    
			conn = site.openConnection();
			conn.setRequestProperty("Cookie", cookies);
			conn.setRequestProperty ( "User-agent", "artup");
			conn.setDoOutput(true);
			OutputStreamWriter wr2 = new OutputStreamWriter(conn.getOutputStream());
			wr2.write(data);
			wr2.flush();
			  
			BufferedReader rd2 = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			String response2 = "";
			String s2;
			while ((s2 = rd2.readLine()) != null) {
				response2 += s2;
			}
			//conn.
		return "username: "+ userName + " art: " +art +" N: "+N+" E: "+E+" datum: " +datum + " Lokal: " + lokal + " Nogr: "+ngr+ " Cookies: " + cookies + " Response1: \n" + response + "\n\n\n Response2: \n" + response2;
	}
	
	private class WebbConnection extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... data) {
			//ArrayList<Cookie> cookies = new ArrayList<Cookie>();
			try {
				SharedPreferences settings = getPreferences(0);
				String username = settings.getString("username", "");
				String pswrd = settings.getString("username2", "");
				String ngr = settings.getString("nogr", "250");
				//String c =  login(username, pswrd, );
				String wp = rapportera(username, pswrd, data[0], data[1], data[2], data[3], data[4], ngr, new Integer(data[5]).intValue());
				return wp;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				return "error";
			}
			//return username +", " + pswrd +", "+ data[0] +", " + new Integer(data[1]).intValue() +  ", " + new Integer(data[2]).intValue()+", "+ new Integer(data[3]).intValue();
		}
		@Override
		protected void onPostExecute(String result) {
			//Toast.makeText( getApplicationContext(), result, 100000).show();
			TextView t=(TextView)findViewById(R.id.svar); 
    	    t.setText(result);
		}
	}
	
	public void readWebpage() {
		TextView t=(TextView)findViewById(R.id.art); 
		String art = t.getText().toString();
		t=(TextView)findViewById(R.id.northcoord);
		String N = t.getText().toString();
		t=(TextView)findViewById(R.id.eastcoord);
		String E = t.getText().toString();
		t=(TextView)findViewById(R.id.datumv);
		String datum = t.getText().toString();
		t=(TextView)findViewById(R.id.lokal);
		String lokal = t.getText().toString();
		WebbConnection task = new WebbConnection();
		task.execute(new String[] { art, N, E, datum, lokal, "0" });
	}

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        raportView();
        
    }
}


